const dotenv = require('dotenv')
const envFile = !!process.env.NODE_ENV ? `.env.${process.env.NODE_ENV}` : '.env';
console.log(envFile)
dotenv.config({ path: envFile });

const express = require('express');
const ejs = require('ejs');
const path = require('path');
const axios = require('axios');
const Moment = require('moment');
const fs = require('fs');
const app = express();
const PORT = 3008;
const api = axios.create({
    baseURL: process.env.API_BASEURL
})
api.interceptors.request.use((config) => {
	let headers = {
        ...config.headers,
        'tenant-id': '1'
    }
	return {
		...config,
		headers
	}
}, (error) => {
	// 对请求错误做些什么
	return Promise.reject(error);
});
// 解析 JSON 请求体
app.use(express.json());

// 读取并转换本地图片为 Base64
const imageToBase64 = (imagePath) => {
    try {
        const filePath = path.join(__dirname, imagePath);
        const imageBuffer = fs.readFileSync(filePath);
        const base64Image = imageBuffer.toString('base64');

        // 获取 MIME 类型（如 image/png）
        const ext = path.extname(imagePath).slice(1);
        const mimeType = `image/${ext}`;

        return `data:${mimeType};base64,${base64Image}`;
    } catch (error) {
        console.error("图片转换失败:", error);
        return null;
    }
};

// 订单 API，返回 HTML
app.get('/get-order-html', async (req, res) => {
    console.log(process.env.API_BASEURL)
    console.log(process.env.NODE_ENV)
    try {
        // 渲染 EJS 模板
        const response = await api.post('/admin-api/ins/order/update-paid', req.query);
        const {data: orderData, code, msg } = response.data;
        if (code !== 0) {
            console.log(process.env.API_BASEURL);
            return res.status(200).json({ code: 7002, msg, data: null });
        }
        const order = {
            ...orderData.data,
            payTime: Moment(orderData.data.payTime).format('YYYY-MM-DD HH:mm:ss'),
            policyLimit: orderData.data.policyLimit * 10000,
            expireDate: !!orderData.data.expireDate ? Moment(orderData.data.expireDate).format('YYYY-MM-DD') : Moment(orderData.data.effectiveStartDate).add(1, 'year').add(-1, 'day').format('YYYY-MM-DD'),
            images: {
                logo: imageToBase64('images/l.png'),
                bg: imageToBase64('images/s.jpg')
            }
        }
        const emailHtml = await ejs.renderFile(path.join(__dirname, 'views', 'order-template.ejs'), order);

        // 返回 HTML
        res.send(emailHtml);
    } catch (error) {
        console.error("HTML 生成失败:", error);
        res.status(200).json({ code: 7001, msg: "HTML 生成失败", data: null });
    }
});

app.get('/new-user-html', async (req, res) => {
    console.log(process.env.API_BASEURL)
    console.log(process.env.NODE_ENV)
    try {
        const user = {
            name: "xxx公司",
            password: "7ZGJ55eAsr",
            images: {
                bg: imageToBase64('images/new-user-bg.png')
            }
        }
        const emailHtml = await ejs.renderFile(path.join(__dirname, 'views', 'new-user-template.ejs'), user);

        // 返回 HTML
        res.send(emailHtml);
    } catch (error) {
        console.error("HTML 生成失败:", error);
        res.status(200).json({ code: 7001, msg: "HTML 生成失败", data: null });
    }
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`🚀 服务器运行在 http://localhost:${PORT}`);
});
